package work.linruchang.util.bean.ocr;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.IDCardOCRResponse;
import lombok.Data;
import lombok.SneakyThrows;
import work.linruchang.util.bean.IDCardInfo;

import java.util.List;

/**
 * 腾讯OCR
 *
 * UI在线演示、手动调用：https://cloud.tencent.com/act/event/ocrdemo?dt=1
 * API文档：https://cloud.tencent.com/document/api/866/33517
 * API文档代码以及调用：https://console.cloud.tencent.com/api/explorer?Product=ocr&Version=2018-11-19&Action=IDCardOCR&SignVersion=
 * @author LinRuChang
 * @version 1.0
 * @date 2022/03/30
 * @since 1.8
 **/
@Data
public class TelcentOcr implements OcrInterface {

    private String secretId = "AKIDOcZGjvqUqwlJacNr41h6D3cuud5GBphJ";
    private String secretKey = "NUJr87pGQItCF1XmlTu4xYsvhCQN3SaR";


    /**
     * 识别身份证信息
     *
     * 正面照识别：{"Name":"林如昌","Sex":"男","Nation":"汉","Birth":"1998/1/18","Address":"广东省封开县长安镇长安村委会安和村3号","IdNum":"441225199801183217","Authority":"","ValidDate":"","AdvancedInfo":"{}","RequestId":"c05e9107-e487-4b1d-a788-9dd514ceddd5"}
     * 反面照识别：{"Name":"","Sex":"","Nation":"","Birth":"","Address":"","IdNum":"","Authority":"封开县公安局","ValidDate":"2016.08.09-2026.08.09","AdvancedInfo":"{}","RequestId":"7f05c34f-2ca4-45c8-b8ea-3bca1cd3c8e7"}
     * @param cardImgBase64 身份证图片
     * @param cardSide 身份证的正反面  FRONT正面（头像）  BACK反面（国徽） 不填则第三方OCR自动识别正反照
     * @return IDCardInfo
     */
    @SneakyThrows
    @Override
    public IDCardInfo ocrIDCardByCardSide(String cardImgBase64, String cardSide) {
        Assert.notBlank(secretId, "缺失腾讯OCR【SecretId】，请检查");
        Assert.notBlank(secretKey, "缺失腾讯OCR【SecretKey】，请检查");


        if(StrUtil.isBlank(cardImgBase64)){return null;}

        // 实例化一个认证对象，入参需要传入腾讯云账户secretId，secretKey,此处还需注意密钥对的保密
        // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
        Credential cred = new Credential(secretId, secretKey);
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("ocr.tencentcloudapi.com");
        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        // 实例化要请求产品的client对象,clientProfile是可选的
        OcrClient client = new OcrClient(cred, "ap-guangzhou", clientProfile);
        // 实例化一个请求对象,每个接口都会对应一个request对象
        IDCardOCRRequest req = new IDCardOCRRequest();
        req.setImageBase64(cardImgBase64);
        if(StrUtil.isNotBlank(cardSide)) {
            req.setCardSide(cardSide);
        }

        // 返回的resp是一个IDCardOCRResponse的实例，与请求对象对应
        IDCardOCRResponse resp = client.IDCardOCR(req);

        IDCardInfo idCardInfo = JSON.parseObject(IDCardOCRResponse.toJsonString(resp), IDCardInfo.class);
        String certificateValidityPeriod = idCardInfo.getCertificateValidityPeriod();
        if(StrUtil.isNotBlank(certificateValidityPeriod)) {
            List<String> certificateValidityPeriodDates = StrUtil.split(certificateValidityPeriod, "-");
            int periodLength = 2;
            if(CollUtil.size(certificateValidityPeriodDates) == periodLength) {
                idCardInfo.setCertificateValidityStartDate(DateUtil.parse(certificateValidityPeriodDates.get(0)));
                idCardInfo.setCertificateValidityEndDate(DateUtil.parse(certificateValidityPeriodDates.get(1)));
            }
        }

        return idCardInfo;
    }


}
